using Main.Details;
using Main.Event;
using UnityEngine;
using ZSW.Framework;

namespace Main.Inventory
{
    public class Box : MonoBehaviour
    {
        public InventoryBag_SO boxBagTemplate;
        public InventoryBag_SO boxBag;
        public GameObject mouseIcon;

        public int index;

        private bool canOpen = false;
        private bool isOpen;

        private void OnEnable()
        {
            if (boxBag == null)
            {
                boxBag = Instantiate(boxBagTemplate);
            }
        }

        public void InitBox(int boxIndex)
        {
            this.index = boxIndex;

            var key = this.name + index;

            if (ZSWF_IOCContainer.Get<InventoryManager>().TryGetBoxDataList(key, out var list))
            {
                boxBag.InventoryList = list;
            }
            // 新建箱子
            else
            {
                if (index == 0)
                {
                    index = ZSWF_IOCContainer.Get<InventoryManager>().boxDataDic.Count;
                }
                ZSWF_IOCContainer.Get<InventoryManager>().AddBoxData(this);
            }
        }

        private void OnTriggerEnter2D(Collider2D other)
        {
            if (other.CompareTag("Player"))
            {
                canOpen = true;
                mouseIcon.SetActive(true);
            }
        }

        private void OnTriggerExit2D(Collider2D other)
        {
            if (other.CompareTag("Player"))
            {
                canOpen = false;
                mouseIcon.SetActive(false);
            }
        }
        private void Update()
        {
            if (!isOpen && canOpen && Input.GetMouseButtonDown(1))
            {
                MainEventSystem.CallBaseBagOpenEvent(SlotType.Box, boxBag);

                canOpen = false;
            }

            // 不能打开时
            if (!canOpen && isOpen)
            {
                MainEventSystem.CallBaseBagCloseEvent(SlotType.Box, boxBag);
                isOpen = false;
            }

            if (isOpen && Input.GetKeyDown(KeyCode.Escape))
            {
                MainEventSystem.CallBaseBagCloseEvent(SlotType.Box, boxBag);
                isOpen = false;
            }
        }


    }
}